<template>
  <popup
    ref="popupRef"
    title="新增"
    :async="true"
    width="30%"
    :clickModalClose="true"
    @confirm="handleConfirm"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      label-width="130px"
      :rules="formRules"
      label-position="right"
    >
      <el-form-item label="名称" prop="title">
        <el-input
          v-model="formData.title"
          size="small"
          clearable
          placeholder="请输入名称"
        />
      </el-form-item>
      <el-form-item label="分类">
        <el-select
          class="flex-1"
          v-model="formData.cate_id"
          placeholder="请选择分类"
          size="small"
        >
          <el-option
            v-for="(item, index) in cateList"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="分包负责人">
        <el-input
          v-model="formData.leader"
          size="small"
          clearable
          placeholder="请输入分包负责人"
        />
      </el-form-item>
      <el-form-item label="负责人联系方式">
        <el-input
          v-model="formData.leader_tel"
          size="small"
          clearable
          placeholder="请输入负责人联系方式"
        />
      </el-form-item>
      <el-form-item label="备注">
        <el-input
          v-model="formData.remark"
          type="textarea"
          placeholder="请输入备注"
          autosize
          size="small"
        />
      </el-form-item>
    </el-form>
  </popup>
</template>
<script lang="ts" setup>
import type { FormInstance } from "element-plus";
import { adminAdd, listAll } from "@/api/financial/lists";
import Popup from "@/components/popup/index.vue";
onMounted(() => {
  fetchCateList();
});
const emit = defineEmits(["success", "close"]);
const formRef = shallowRef<FormInstance>();
const popupRef = shallowRef<InstanceType<typeof Popup>>();
const formData = reactive({
  title: "",
  cate_id: "",
  leader: "",
  leader_tel: "",
  remark: "",
});
const formRules = reactive({
  title: [{ required: true, message: "请输入名称", trigger: ["change"] }],
});
// 打开弹窗
const open = () => {
  popupRef.value?.open();
};
// 分类列表
const cateList = ref([]);
const fetchCateList = async () => {
  const data = await listAll({ key: "finance_unit_cate" });
  cateList.value = data;
};
// 表单确认
const handleConfirm = async () => {
  await formRef.value?.validate();
  fetchAdd();
};
const fetchAdd = async () => {
  await adminAdd(formData);
  popupRef.value?.close();
  emit("success");
};
// 表单取消
const handleClose = () => {
  emit("close");
};
defineExpose({ open });
</script>
<style lang="scss" scoped>
:deep(.el-form) {
  .el-form-item {
    margin-bottom: 20px;
  }
}
</style>
